package com.atguigu.daijia.map.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.daijia.common.execption.GuiguException;
import com.atguigu.daijia.common.result.ResultCodeEnum;
import com.atguigu.daijia.map.service.MapService;
import com.atguigu.daijia.model.form.map.CalculateDrivingLineForm;
import com.atguigu.daijia.model.vo.map.DrivingLineVo;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
@SuppressWarnings({"unchecked","rawtypes"})
public class MapServiceImpl implements MapService {

    @Resource
    private RestTemplate restTemplate;


//    //TODO 如果地图报错看是不是这里的value导错包
//    @Value("tencent.cloud.map")
//    private String key;


    @Value("${tencent.map.key}")
    private String key;


    //计算驾驶路线
    @Override
    public DrivingLineVo calculateDrivingLine(CalculateDrivingLineForm calculateDrivingLineForm) {
        //请求腾讯提供的接口，按照接口要求传递参数，返回需要结果
        //使用HttpClinet，目前Spring封装调用工具RestTemplate
        //定义调用腾讯地址
        String url =  "https://apis.map.qq.com/ws/direction/v1/driving/?from={from}&to={to}&key={key}";

        //封装传递参数
        HashMap<String, String> map = new HashMap<>();

        //开始位置
        //经纬度，比如：北纬40，东经116
        map.put("from",calculateDrivingLineForm.getStartPointLatitude()+","+calculateDrivingLineForm.getStartPointLongitude());
        //结束位置
        map.put("to",calculateDrivingLineForm.getEndPointLatitude()+","+calculateDrivingLineForm.getEndPointLongitude());
        //key
        map.put("key",key);

        //使用redisTemplate调用get
        //JSONObject意思是返回的将json字符传转换成一个对应的实体类
        JSONObject result = restTemplate.getForObject(url, JSONObject.class, map);

        //判断是否调用成功
        //这种排错形接口一般返回的都是0
        int status = result.getIntValue("status");
        if(status != 0){
            throw new GuiguException(ResultCodeEnum.MAP_FAIL);
        }

        //获取返回路线信息
        JSONObject route =
                result.getJSONObject("result").getJSONArray("routes").getJSONObject(0);

        //创建vo对象
        DrivingLineVo drivingLineVo = new DrivingLineVo();
        //预估时间，route是访问腾讯接口返回的一个结果，所以route。getBigDecimal（）是可以直接得到预估时间的
        drivingLineVo.setDuration(route.getBigDecimal("diration"));
        //距离
        drivingLineVo.setDistance(route.getBigDecimal("distance")
                //将米化单位为千米，并保留两位小数，向上取整数
                .divide(new BigDecimal(1000))
                .setScale(2, RoundingMode.HALF_UP));
        //路线
        drivingLineVo.setPolyline(route.getJSONArray("polyline"));
        return drivingLineVo;
    }
}
